/*
 *    This file is part of BlobDB.
 *
 *    BlobDB is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    BlobDB is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with BlobDB.  If not, see <http://www.gnu.org/licenses/>.
 *    
 *    Copyright(c) 2011 Michael Kankkonen
 *    http://www.vnetcon.org
 */


package org.vnetcon.blobdb.database.backend.file;

import java.util.ArrayList;

import org.vnetcon.blobdb.database.backend.TransactionInterface;
import org.vnetcon.blobdb.database.backend.file.fdo.Table;
import org.vnetcon.blobdb.database.backend.file.fdo.TableData;
import org.vnetcon.blobdb.database.backend.file.fdo.TableID;

public class FileTransaction implements TransactionInterface {

	private ArrayList<TableData> aTableDataInTransaction = new ArrayList<TableData>();
	private ArrayList<Table> aTableInTransaction = new ArrayList<Table>();
	private ArrayList<TableID> aTableIDInTransaction = new ArrayList<TableID>();
	private boolean inTransaction = false;
	
	@Override
	public void begin() {
		this.inTransaction = true;
	}

	@Override
	public void commit() {
		int i = 0;
		while(i < this.aTableDataInTransaction.size()){
			TableData buf = this.aTableDataInTransaction.get(i);
			buf.save();
			i++;
		}
		this.aTableDataInTransaction.clear();

		i = 0;
		while(i < this.aTableInTransaction.size()){
			Table buf = this.aTableInTransaction.get(i);
			buf.save();
			i++;
		}
		this.aTableInTransaction.clear();

		i = 0;
		while(i < this.aTableIDInTransaction.size()){
			TableID buf = this.aTableIDInTransaction.get(i);
			buf.save();
			i++;
		}
		this.aTableIDInTransaction.clear();
		
		this.inTransaction = false;
	}

	@Override
	public void rollback() {
		int i = 0;
		while(i < this.aTableDataInTransaction.size()){
			TableData buf = this.aTableDataInTransaction.get(i);
			buf.rollback();
			i++;
		}
		this.aTableDataInTransaction.clear();
		this.inTransaction = false;
	}
	
	public boolean isTransactionBegin(){
		return this.inTransaction;
	}
	
	public void close(){
		if(this.inTransaction){
			this.rollback();
		}
	}

	public void finalize() {
		close();
	}

	public void addToTransaction(Table table){
		this.aTableInTransaction.add(table);
	}

	public void addToTransaction(TableID table){
		this.aTableIDInTransaction.add(table);
	}

	public void addToTransaction(TableData tabledata){
		this.aTableDataInTransaction.add(tabledata);
	}
	
}
